package com.softer.wxzj.service.impl;/**
 * @author Gong Zhiyang
 * @date 2019/6/28
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.*;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowTypeEnum;
import com.softer.wxzj.common.flow.util.FlowAuditUtil;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.DepositApplyService;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author Gong Zhiyang
 * @date 2019/6/28
 */
@Service
public class DepositApplyServiceImpl implements DepositApplyService {
    @Autowired
    private DepositApplyMapper depositApplyMapper;
    @Autowired
    private DepReqListInfoMapper depReqListInfoMapper;
    @Autowired
    private DepReqMapper depReqMapper;
    @Autowired
    private BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    private BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    private BaseRegionInfoMapper baseRegionInfoMapper;
    @Autowired
    private AccKeepAccountMapper accKeepAccountMapper;
    @Autowired
    private SysCoreParamMapper sysCoreParamMapper;
    @Autowired
    private DepModeInfoMapper depModeInfoMapper;
    @Autowired
    private FlowAuditUtil flowUtil;
    @Autowired
    private BaseOwnerInfoMapper baseOwnerInfoMapper;

    /**
     * 精确/模糊查询 交存申请查询列表
     *
     * @param page           分页实体
     * @param baseRegionInfo 查询实体
     * @param fuzzy          模糊查询字段
     * @return 交存申请查询列表
     */
    @Override
    public PageInfo<BaseRegionInfo> getDepositApplyList(Page page, BaseRegionInfo baseRegionInfo, String fuzzy) {
        String flowState = String.valueOf(NumberEnum.TWO.getNum());
        baseRegionInfo.setFlowState(flowState);
        List<BaseRegionInfo> list;
        String zoneCode = OperUtil.zoneCodeUtil.getZoneCode();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (StringUtils.isBlank(fuzzy)) {
            //精确查询
            baseRegionInfo.setLoginZoneCode(zoneCode);
            list = depositApplyMapper.getDepositApplyList(baseRegionInfo);
        } else {
            //模糊查询
            list = depositApplyMapper.fuzzySearch(fuzzy, zoneCode, baseRegionInfo.getState(), flowState);
        }
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<DepositApply> findDepositApplyList(Page page, DepositApply depositApply) {
        String zoneCode = OperUtil.zoneCodeUtil.getZoneCode();
        depositApply.setZoneCode(zoneCode);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<DepositApply> list = depositApplyMapper.findDepositApplyList(depositApply);
        return new PageInfo(list);
    }

    /**
     * 精确/模糊查询 根据申请ID查询申请明细
     *
     * @param page         分页实体
     * @param depositAudit 查询实体
     * @param fuzzy        模糊查询字段
     * @return 申请明细
     */
    @Override
    public PageInfo<DepositAudit> getListByReqId(Page page, DepositAudit depositAudit, String fuzzy) {
        List<DepositAudit> list;
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (StringUtils.isBlank(fuzzy)) {
            //精确查询
            list = depositApplyMapper.getListByReqId(depositAudit);
        } else {
            //模糊查询
            list = depositApplyMapper.fuzzyByReqId(fuzzy, depositAudit.getId());
        }
        list.stream().forEach(x -> {
            String address = depositApplyMapper.getAddress(x.getHouseId());
            x.setAddress(address);
        });
        PageInfo<DepositAudit> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 精确/模糊查询 根据申请ID查询申请明细的本页合计和总合计
     *
     * @param page         分页实体
     * @param depositAudit 查询实体
     * @param fuzzy        模糊查询字段
     * @return 申请明细的本页合计和总合计
     */
    @Override
    public List<DepositAudit> getTotalByReqId(Page page, DepositAudit depositAudit, String fuzzy) {
        List<DepositAudit> list = new ArrayList<>();
        if (StringUtils.isBlank(fuzzy)) {
            //精确查询
            DepositAudit totalAmount = depositApplyMapper.getTotalByReqId(depositAudit);
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            List<DepositAudit> pageList = depositApplyMapper.getListByReqId(depositAudit);
            setName(list, totalAmount, pageList);
        } else {
            //模糊查询
            DepositAudit totalAmount = depositApplyMapper.fuzzyTotalByReqId(fuzzy, depositAudit.getId());
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            List<DepositAudit> pageList = depositApplyMapper.fuzzyByReqId(fuzzy, depositAudit.getId());
            setName(list, totalAmount, pageList);
        }
        return list;
    }

    /**
     * 批量查询交存清册
     *
     * @param page      分页实体
     * @param reqIdList 交存申请ID集合
     * @return 清册列表
     */
    @Override
    public PrintList batchPrintList(Page page, String reqIdList) {
        PrintList printList = new PrintList();
        //交存申请ID集合
        List<String> list = Arrays.asList(reqIdList.split(","));
        List<Integer> numList = new ArrayList<>();
        for (String id : list) {
            int num = depositApplyMapper.countNum(id);
            numList.add(num);
        }
        printList.setNumList(numList);
        int pageNum = page.getPageNum();
        for (int i = 0; i < list.size(); i++) {
            DepositAudit depositAudit = new DepositAudit();
            depositAudit.setId(list.get(i));
            if (pageNum * page.getPageSize() > numList.get(i)) {
                //计算当前的条数能够分成多少页
                int limit;
                int remainder = numList.get(i) % page.getPageSize();
                if (remainder == NumberEnum.ZERO.getNum()) {
                    //能整除，不需要加一页
                    limit = numList.get(i) / page.getPageSize();
                } else {
                    //b不能整除，需要加一页
                    limit = numList.get(i) / page.getPageSize() + 1;
                }
                if (pageNum > limit) {
                    pageNum = pageNum - limit;
                    continue;
                }
            }
            PageHelper.startPage(pageNum, page.getPageSize());
            List<DepositAudit> listByReqId = depositApplyMapper.getListByReqId(depositAudit);
            DepositAudit totalAmount = depositApplyMapper.getTotalByReqId(depositAudit);
            setName(listByReqId, totalAmount, listByReqId);
            printList.setList(listByReqId);
            printList.setTotalMoney(totalAmount.getPayAmount());
            printList.setHouseNum(numList.get(i));
            //查询表头信息
            PrintList p = depositApplyMapper.getHeadMsg(list.get(i));
            printList.setNo(p.getNo());
            printList.setRegionName(p.getRegionName());
            printList.setBankName(p.getBankName());
            printList.setReqName(p.getReqName());
            printList.setTotal(numList.stream().reduce(Integer::sum).orElse(0));
            break;
        }
        return printList;
    }

    @Override
    public PageInfo<DepReq> subimtDepReqList(Page page, DepReq depReq) {
        //查询登陆账号管理下待审核业务ID和管理区域
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.DEPOSIT_DEVELOP.getType());
        List<DepReq> list = new ArrayList<>();
        if (null != map) {
            //精确查询
            depReq.setId(map.get("id"));
            // 用户绑定的区域
            depReq.setZoneCode(map.get("zoneCode"));
            //业务表的审核状态 1审核中
            depReq.setFlowState(String.valueOf(NumberEnum.ONE.getNum()));
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = depReqMapper.getAuditListByDepReq(depReq);
        }
        PageInfo<DepReq> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<DepReq> getAllDepReqList(Page page, DepReq depReq) {
        //模糊查询
        String zoneCode = OperUtil.zoneCodeUtil.getZoneCode();
        depReq.setZoneCode(zoneCode);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<DepReq> list = depReqMapper.getAllDepReqList(depReq);
        PageInfo<DepReq> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 添加撤销表
     *
     * @param depReq
     */
    public void revocation(DepReq depReq, String depType, String uuid) {
        DepRevocat depRevocat = new DepRevocat();
        depRevocat.setNo(depReq.getNo());
        depRevocat.setBusinessId(depReq.getId());
        depRevocat.setNum(depReq.getTotalNum());
        depRevocat.setType("1");
        depRevocat.setValidDate(depReq.getValidDate());
        depRevocat.setDepType(depType);
        depRevocat.setCreater(ShiroUserUtil.getUserName());
        depRevocat.setCreateTime(DateUtils.getNow());
        depRevocat.setId(uuid);
        int num = depReqListInfoMapper.depAdd(depRevocat);
        if (num == 0) {
            throw new CourseException(201, "添加撤销表操作失败");
        }
    }

    /**
     * 撤销详情
     *
     * @param uuid 撤销表dep_revocat的ID
     * @param d    交存表数据
     * @return 撤销表实体
     */
    public DepRevocatDetail revocationList(String uuid, DepReqListInfo d) {
        DepRevocatDetail depRevocatDetail = new DepRevocatDetail();
        depRevocatDetail.setId(UUIDUtil.getUUID());
        depRevocatDetail.setReqlistId(d.getId());
        depRevocatDetail.setRevocatId(uuid);
        depRevocatDetail.setCreater(ShiroUserUtil.getUserName());
        depRevocatDetail.setDeferAccr(d.getDeferAccr());
        depRevocatDetail.setDueAmount(d.getDueAmount());
        depRevocatDetail.setPayAmount(d.getPayAmount());
        depRevocatDetail.setDepDate(d.getDepDate());
        return depRevocatDetail;
    }

    /**
     * 资金补齐撤销
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public CommonResult findDeposiy(String id) {
        DepReq depReq = depReqMapper.getInfo(id);
        if (!depReq.getState().equals("1")) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该申请状态不一致，无法撤销");
        }
        if (depReq.getStep().equals("5") && depReq.getState().equals("1")) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该申请已经记账，无法撤销");
        }
        String uuid = UUIDUtil.getUUID();
        //添加撤销表
        revocation(depReq, "1", uuid);
        List<DepRevocatDetail> depRevocatDetails = new ArrayList<>();
        List<DepReqListInfo> depReqListInfo = depReqListInfoMapper.getInfoByDepReqId(id);
        for (DepReqListInfo d : depReqListInfo) {
            DepRevocatDetail depRevocatDetail = revocationList(uuid, d);
            depRevocatDetails.add(depRevocatDetail);
        }
        int num = depReqListInfoMapper.addDepRevocateDetail(depRevocatDetails);
        if (num == 0) {
            throw new CourseException(201, "添加撤销详情表操作失败");
        }
        //acck 修改状态
        num = accKeepAccountMapper.updateState("0", depReq.getNo());
        if (num == 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改记账表操作失败");
        }
        //dep_req 修改状态
        num = depReqMapper.updateState(id, "0");
        if (num == 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改申请表操作失败");
        }
        //house修改状态
        BaseOwnerInfo b = depReqListInfoMapper.getAllByDepReqId(id);
        //dep_req_list  修改状态
        num = depReqListInfoMapper.updateStateByDepReqState(id);
        if (num == 0) {
            throw new CourseException(201, "修改申请详情表操作失败");
        }
        num = baseHouseInfoMapper.updateOwnerStateAndPross(b.getAccNo(), "0", "0");
        if (num == 0) {
            throw new CourseException(201, "修改房屋表操作失败");
        }
        //owner 业主id
        num = baseOwnerInfoMapper.updatAllState(b.getOwnerNo(), "0");
        if (num == 0) {
            throw new CourseException(201, "修改业主表操作失败");
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    public PageInfo<DepReq> submitDepList(Page page, DepReq depReq) {
        //模糊查询
        String zoneCode = OperUtil.zoneCodeUtil.getZoneCode();
        depReq.setZoneCode(zoneCode);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<DepReq> list = depReqMapper.submitDepList(depReq);
        PageInfo<DepReq> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    private void setName(List<DepositAudit> list, DepositAudit totalAmount, List<DepositAudit> pageList) {
        BigDecimal dueAmount = pageList.stream().map(DepositAudit::getDueAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal payAmount = pageList.stream().map(DepositAudit::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal struArea = pageList.stream().map(DepositAudit::getStruArea).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal deferAccr = pageList.stream().map(DepositAudit::getDeferAccr).reduce(BigDecimal.ZERO, BigDecimal::add);
        DepositAudit pageAmount = new DepositAudit();
        pageAmount.setDueAmount(dueAmount);
        pageAmount.setPayAmount(payAmount);
        pageAmount.setStruArea(struArea);
        pageAmount.setDeferAccr(deferAccr);
        pageAmount.setName("本页合计");
        totalAmount.setName("总合计");
        list.add(totalAmount);
        list.add(pageAmount);
    }

    /**
     * 精确/模糊查询 根据小区ID查询申请列表
     *
     * @param page         分页实体
     * @param depositApply 查询实体
     * @param fuzzy        模糊查询字段
     * @return 申请列表
     */
    @Override
    public PageInfo<DepositApply> getListByRegionId(Page page, DepositApply depositApply, String fuzzy) {
        List<DepositApply> list;
        if (StringUtils.isBlank(fuzzy)) {
            //精确查询
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = depositApplyMapper.getListByRegionId(depositApply);
        } else {
            //模糊查询
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = depositApplyMapper.fuzzyByRegionId(fuzzy, depositApply.getId());
        }
        PageInfo<DepositApply> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 查询代缴企业列表
     *
     * @param id 小区ID
     * @return 企业列表
     */
    @Override
    public List<BaseOrganization> getOrganization(String id) {
        return depositApplyMapper.getAllOrganization(id);
    }

    /**
     * 查询业主自交列表或者企业代缴申请列表
     *
     * @param page         分页实体
     * @param depositAudit 查询实体
     * @param fuzzy        模糊查询字段
     * @return 申请列表
     */
    @Override
    public PageInfo<DepositAudit> getDepositApplyListByRegionId(Page page, DepositAudit depositAudit, String fuzzy) {
        String flowState = String.valueOf(NumberEnum.TWO.getNum());
        String state = NumStrEnum.TWO.getNum();
        depositAudit.setState(state);
        depositAudit.setFlowState(flowState);
        List<DepositAudit> list;
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (StringUtils.isBlank(fuzzy)) {
            //精确查询
            list = depositApplyMapper.getDepositApplyListByRegionId(depositAudit);
        } else {
            //模糊查询
            list = depositApplyMapper.fuzzyDepositApplyListByRegionId(fuzzy, depositAudit.getId(), flowState);
        }
        for (DepositAudit dep : list) {
            dep.setCreateTime(DateUtils.getDateNow());
        }
        PageInfo<DepositAudit> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 交存申请
     *
     * @param list      申请id列表
     * @param type      交存模式（00 为自缴 01为企业代缴）
     * @param validDate 申请有效日期
     * @param corpNo    开发商ID
     * @return 详情列表
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public synchronized CommonResult depositAudit(List<String> list, String type, String validDate, String corpNo) {
        String p = "";
        String payType = "";
        String param = NumStrEnum.ZERO.getNum();
        //延期利息
        if (list == null || list.size() == 0) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "请至少选择一条交存申请");
        }
        /**
         * 1,新增交存申请
         * 2,修改交存详情表，绑定交存申请，修改详情状态
         */
        if (DepositEnum.SELF_DEPOSIT.getCode().equals(type)) {
            //自交,新增多条申请
            for (String id : list) {
                if (depReqMapper.selectByDepReqList(id) > 0) {
                    throw new CourseException(201, "该数据已经申请或撤销请刷新页面重试");
                }
                //计算应交总金额和实缴总金额
                DepReq depReq = getAmount(id);
                String uuid = UUIDUtil.getUUID();
                //查询申请人:自交时，申请人为业主
                String reqName = depositApplyMapper.getSelfName(id);
                //2,修改详情表，绑定交存申请，修改详情状态
                updateDetail(uuid, id, new BigDecimal(NumberEnum.ZERO.getNum()));
                //1,新增交存申请
                addDepReq(id, type, validDate, uuid, null, NumberEnum.ONE.getNum(), depReq, reqName);

            }
        } else if (DepositEnum.BEHALF_DEPOSIT.getCode().equals(type)) {
            //系统参数查看有没有延期利息
            String no = sysCoreParamMapper.getParamValueByCode(NumStrEnum.FIVE.getNum());
            if (StringUtils.isNotEmpty(no) || !(String.valueOf(NumberEnum.ZERO.getNum())).equals(no)) {
                p = sysCoreParamMapper.getParamValueByCode("16");
                if (!(String.valueOf(NumberEnum.ZERO.getNum())).equals(p)) {
                    //查看延期利息计算利率或金额
                    param = sysCoreParamMapper.getParamValueByCode("52");
                    //计算方式
                    payType = sysCoreParamMapper.getParamValueByCode("15");
                }
            }
            //代缴，新增申请
            String ids = String.join(",", list);
            //查询是不是一个银行
            List<DepReq> depReqs = depReqMapper.sumByBankId(ids);
            //计算应交总金额和实缴总金额
            for (DepReq d : depReqs) {
                DepReq depReq = new DepReq();
                String uuid = UUIDUtil.getUUID();
                //2,修改详情表，绑定交存申请，修改详情状态
                String[] arr = d.getIds().split(",");
                List<String> idList = Arrays.asList(arr);
                for (String s : idList) {
                    BigDecimal moneyOut = BigDecimal.ZERO;
                    if ((NumStrEnum.TWO.getNum()).equals(payType)) {
                        DepReqListInfo depReqListInfo = depReqListInfoMapper.getInfo(s);
                        LocalDate start = LocalDate.parse(depReqListInfo.getDepDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        LocalDate dateNow = LocalDate.parse(DateUtils.getDateNow(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        long days = Long.parseLong(p);
                        if (start.plusDays(days).compareTo(dateNow) < 0) {
                            //差了多少天
                            String howDay = String.valueOf(dateNow.toEpochDay() - start.plusDays(days).toEpochDay());
                            BigDecimal num1 = new BigDecimal(howDay);
                            BigDecimal num2 = new BigDecimal(param);
                            //dep_req_list表的延期利息
                            moneyOut = num1.multiply(num2);
                            //计算dep_req表的延期利息
                            if (null == depReq.getDeferAccr()) {
                                depReq.setDeferAccr(BigDecimal.ZERO);
                            }
                        }
                    }
                    updateDetail(uuid, s, moneyOut);
                }
                //查询申请人:代缴时，申请人为代缴开发商
                String reqName = depositApplyMapper.getBehalfName(corpNo);
                //1,新增交存申请
                addDepReq(idList.get(0), type, validDate, uuid, corpNo, idList.size(), depReq, reqName);
            }
        } else {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "该交存模式不存在");
        }
        return CommonResult.ResponseResult(200);
    }

    /**
     * 计算应交总金额和实缴总金额
     *
     * @param id 交存业务ID集合
     * @return 应交总金额和实缴总金额
     */
    private DepReq getAmount(String id) {
        //计算应交总金额和实缴总金额
        DepReq depReq = depositApplyMapper.count(id);
        if (depReq == null) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        return depReq;
    }

    /**
     * 1,新增交存申请
     *
     * @param type      交存模式（00 为自缴 01为企业代缴）
     * @param validDate 申请有效日期
     * @param uuid      申请ID
     * @param corpNo    开发商ID
     * @param req       应交总金额和实缴总金额
     */
    private void addDepReq(String id, String type, String validDate, String uuid, String corpNo, int num, DepReq req, String reqName) {
        DepReq depReq = new DepReq();
        depReq.setId(uuid);
        depReq.setType("0");
        depReq.setCorpType(type);
        String userName = ShiroUserUtil.getUserName();
        depReq.setCreater(userName);
        depReq.setModifier(userName);
        depReq.setReqOper(reqName);
        String no = DepositUtil.getNo(NumberEnum.ONE.getNum().toString());
        depReq.setNo(no);
        depReq.setStep(String.valueOf(NumberEnum.THREE.getNum()));
        depReq.setValidDate(validDate);
        depReq.setCorpNo(corpNo);
        depReq.setTotalNum(num);
        depReq.setState(String.valueOf(NumberEnum.ONE.getNum()));
        List<DepReqListInfo> d = depReqListInfoMapper.getInfoByDepReqId(uuid);
        BigDecimal depReqMoney = BigDecimal.ZERO;
        BigDecimal fundAmount = BigDecimal.ZERO;
        BigDecimal dueAmount = BigDecimal.ZERO;

        for (DepReqListInfo info : d) {
            if (null != info.getDeferAccr()) {
                depReqMoney = depReqMoney.add(info.getDeferAccr());
            }
            if (null != info.getPayAmount()) {
                fundAmount = fundAmount.add(info.getPayAmount());
            }
            if (null != info.getDueAmount()) {
                dueAmount = dueAmount.add(info.getDueAmount());
            }
        }
        depReq.setFundAmount(dueAmount);
        depReq.setTotalAmount(fundAmount);
        depReq.setDeferAccr(depReqMoney);
        DepReqListInfo depReqListInfo = depReqListInfoMapper.selectById(id);
        BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(depReqListInfo.getBuildId());
        depReq.setBankCode(baseBuildInfo.getBankCode());
        AccKeepAccount accKeepAccount = new AccKeepAccount();
        int count = depReqMapper.insert(depReq);
        if (count == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        if (("00").equals(type)) {
            BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(depReqListInfo.getHouseId());
            accKeepAccount.setRemark(baseHouseInfo.getHouseSite() + "交存");
        } else {
            accKeepAccount.setRemark(baseRegionInfoMapper.getInfo(baseBuildInfo.getRegionNo()).getRegionName() + baseBuildInfo.getBuildName() + "交存");
        }
        accKeepAccount.setReqName(reqName);
        accKeepAccount.setBusiNo(depReq.getNo());
        accKeepAccount.setBusiType("311");
        accKeepAccount.setCreateTime(DateUtils.getDateNow());
        accKeepAccount.setCreater(ShiroUserUtil.getUserName());
        accKeepAccount.setBankCode(depReq.getBankCode());
        accKeepAccount.setPayAmount(fundAmount);
        accKeepAccount.setAccountState(NumStrEnum.ZERO.getNum());
        accKeepAccount.setState(NumStrEnum.ONE.getNum());
        accKeepAccount.setSpecialAccount("325");
        accKeepAccount.setVaildDate(depReq.getValidDate());
        accKeepAccount.setRegionId(baseBuildInfo.getRegionNo());
        accKeepAccount.setGrantreqNum(depReq.getNo());
        count = accKeepAccountMapper.insert(accKeepAccount);
        if (count == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
    }

    /**
     * 2,修改详情表，绑定交存申请，修改详情状态
     *
     * @param uuid 申请ID
     * @param id   业务ID
     */
    public void updateDetail(String uuid, String id, BigDecimal money) {
        int num = depositApplyMapper.updateDetail(uuid, id, ShiroUserUtil.getUserName(), money);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }

    }

    /**
     * 获取刚交存申请的打印通知单列表
     *
     * @param list 业务id列表
     * @return 打印通知单列表
     */
    @Override
    public List<DepositAudit> getPrintList(List<String> list) {
        if (list == null || list.size() == 0) {
            return new ArrayList<>();
        }
        String ids = String.join(",", list);
        //查询业务id关联的申请id
        List<String> reqIdList = depositApplyMapper.getDepReqIdList(ids);
        if (reqIdList == null || reqIdList.size() == 0) {
            return new ArrayList<>();
        }
        String join = String.join(",", reqIdList);
        List<DepositAudit> auditList = depositApplyMapper.getAuditList(join);
        //获取刚交存申请的打印通知单列表
        if (auditList == null || auditList.size() == 0) {
            return new ArrayList<>();
        }
        for (DepositAudit depositAudit : auditList) {
            BigDecimal fund = BigDecimal.ZERO;
            List<DepReqListInfo> depReqListInfo = depReqListInfoMapper.getInfoByDepReqId(depositAudit.getId());
            for (DepReqListInfo de : depReqListInfo) {
                if (null != de.getDueAmount()) {
                    fund = fund.add(de.getDueAmount());
                }
            }
            String id = depositAudit.getId();
            //获取业主姓名
            String name = depositApplyMapper.getUserName(id);
            depositAudit.setOwnerName(name);
            //应缴金额
            depositAudit.setFundAmount(fund);
            //小区地址
            BaseHouseInfo base = baseHouseInfoMapper.getInfo(depReqListInfo.get(0).getHouseId());
            BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(base.getBuildNo());
            BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfo(baseBuildInfo.getRegionNo());
            depositAudit.setRegionName(baseRegionInfo.getRegionName());
            List<DepReqListInfo> d = depReqListInfoMapper.getInfoByDepReqId(depositAudit.getId());
            depositAudit.setNum(d.size());
            DepReq info = depReqMapper.getInfo(reqIdList.get(0));
            if ("00".equals(info.getCorpType())) {
                //需要查询房屋地址
                BaseHouseInfo houseInfo = depositApplyMapper.getHouseSite(id);
                depositAudit.setDepyTypeName(houseInfo.getDepyTypeName());
                depositAudit.setHouseSite(houseInfo.getHouseSite());
                depositAudit.setFirstMode(houseInfo.getFirstMode());
                depositAudit.setStruArea(houseInfo.getStruArea());
            }
        }
        return auditList;
    }

    @Override
    public CommonResult updateDepositApplyNo(String startNo, String endNo, String startWith) {
        //获取 no 大于 起始no的列表  从小到大排序
        int length = Integer.valueOf(endNo) - Integer.valueOf(startNo) + 1;
        var infoList = depositApplyMapper.getDepositApplyListfterStareWith(startWith);
        infoList.forEach(x -> {
            //TODO 凭证暂时不做,待进一步确定需求
        });
        return CommonResult.ResponseResult(1);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult depositApplyRevocation(String depositApplyIds) {
        CommonResult commonResult = null;
        var ids = depositApplyIds.split(",");
        for (String id : ids) {
            DepReq depReq = depReqMapper.getInfo(id);
            DepReqListInfo depReqListInfo = new DepReqListInfo();
            depReqListInfo.setDepReqId(id);
            List<DepReqListInfo> list = depReqListInfoMapper.getList(depReqListInfo);
            var uuid = UUIDUtil.getUUID();
            int num = 0;
            for (DepReqListInfo x : list) {
                if (!x.getState().equals(NumStrEnum.THREE.getNum())) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该数据已记账或撤销，请刷新页面重试");
                }
                /*
                缴存申请撤销  1、向核销记录明细表记一下 维护 信息 2、该条维护 申请号删掉  state改成 0申请已撤销
                 */
                DepRevocatDetail depRevocatDetail = revocationList(uuid, x);
                depReqListInfoMapper.dep_revocat_detailDdInsert(depRevocatDetail);
                //申请撤销后，状态变为维护
                num = depReqListInfoMapper.updateToRemove(NumStrEnum.TWO.getNum(), x.getId(), ShiroUserUtil.getUserName(), x.getDeferAccr());
                if (num < 1) {
                    return CommonResult.ResponseResult(num);
                }
            }
            num = accKeepAccountMapper.updateState(NumStrEnum.ZERO.getNum(), depReqMapper.getInfo(id).getNo());
            if (num < 1) {
                return CommonResult.ResponseResult(num);
            }
            depReqListInfoMapper.dep_revocatDoInsert(uuid, NumStrEnum.ONE.getNum(), id, ShiroUserUtil.getUserName(), DateUtils.getNow(), depReq.getTotalNum(), depReq.getNo());
            commonResult = CommonResult.ResponseResult(depositApplyMapper.updateState(NumStrEnum.ZERO.getNum(), id));
            num = depReqMapper.updateToRemove(id, NumStrEnum.ZERO.getNum(), BigDecimal.ZERO);
            if (num < 1) {
                return CommonResult.ResponseResult(num);
            }
        }
        return commonResult;
    }

    @Override
    public DepositApply getInfo(String id) {
        return depositApplyMapper.getInfo(id);
    }

    @Override
    public CommonResult updateValidDate(DepositApply depositApply) {
        depositApply.setModifier(ShiroUserUtil.getUserName());
        DepReq depReq = depReqMapper.getInfo(depositApply.getId());
        AccKeepAccount accKeepAccount = new AccKeepAccount();
        accKeepAccount.setBusiNo(depReq.getNo());
        accKeepAccount.setVaildDate(depositApply.getValidDate());
        accKeepAccountMapper.updateValidDate(accKeepAccount);
        return CommonResult.ResponseResult(depositApplyMapper.updateValidDate(depositApply));
    }

    /**
     * 催缴打印列表
     *
     * @param page           分页实体
     * @param baseRegionInfo 查询实体
     * @return 列表
     */
    @Override
    public PageInfo<BaseRegionInfo> printCall(Page page, BaseRegionInfo baseRegionInfo) {
        String zoneCode = OperUtil.zoneCodeUtil.getZoneCode();
        baseRegionInfo.setZoneCode(zoneCode);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        //如果fuzzy不为空，则模糊查询；为空进行精确查询
        List<BaseRegionInfo> list = depositApplyMapper.getPrintCallList(baseRegionInfo);
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据小区ID查询催缴打印列表
     *
     * @param page          分页实体
     * @param baseHouseInfo 查询实体
     * @return 列表
     */
    @Override
    public PageInfo<BaseHouseInfo> printCallByRegionId(Page page, BaseHouseInfo baseHouseInfo) {
        List<BaseHouseInfo> list;
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        //如果fuzzy不为空，则模糊查询；为空进行精确查询
        if (StringUtils.isBlank(baseHouseInfo.getFuzzy())) {
            //精确查询
            list = depositApplyMapper.printCallByRegionId(baseHouseInfo);
        } else {
            //模糊查询
            list = depositApplyMapper.fuzzyPrintCallByRegionId(baseHouseInfo.getFuzzy(), baseHouseInfo.getId());
        }
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 通知书打印
     * 补打和交存凭证打印，查询的是所有记账后的数据，state=4；
     * 交存通知打印，查询的是申请后，未记账的数据，state=3
     *
     * @param page         分页实体
     * @param depositApply 查询实体
     * @return 打印列表
     */
    @Override
    public PageInfo<DepositApply> printNotice(Page page, DepositApply depositApply) {
        String zoneCode = OperUtil.zoneCodeUtil.getZoneCode();
        depositApply.setZoneCode(zoneCode);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<DepositApply> list = depositApplyMapper.printNotice(depositApply);
        for (DepositApply dep : list) {
            int num = depositApplyMapper.selectNum(dep.getId(), depositApply.getState());
            dep.setCreateTime(DateUtils.getDateNow());
            dep.setNum(num);
//          BaseHouseInfo baseHouseInfo=  baseHouseInfoMapper.getInfo(dep.getHouseId()) ;
//       DepModeInfo depModeInfo=   depModeInfoMapper.getInfo(baseHouseInfo.getFirstMode());
//            dep.setRatio(depModeInfo.getRatio());
//            dep.setFirstMode(depModeInfo.getDepType());
            if (("00").equals(dep.getCorpType())) {
                if (null != baseHouseInfoMapper.getInfo(dep.getHouseId())) {
                    dep.setHouseSite(baseHouseInfoMapper.getInfo(dep.getHouseId()).getHouseSite());
                }
            }
        }
        PageInfo<DepositApply> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public String time(String corpType) {
        String time = "";
        String param;
        LocalDate getHfmpDate = LocalDate.parse(DateUtils.getDateNow(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (("00").equals(corpType)) {
            param = sysCoreParamMapper.getParamValueByCode(NumStrEnum.NINE.getNum());
        } else {
            param = sysCoreParamMapper.getParamValueByCode("12");
        }
        if (StringUtils.isNotBlank(param)) {
            long day = Long.parseLong(param);
            time = getHfmpDate.plusDays(day).toString();
        }
        return time;
    }
}
